package cn.anecansaitin.whimsy.util;

import net.minecraft.world.phys.Vec3;
import org.joml.Vector3d;
import org.joml.Vector3dc;
import org.joml.Vector3f;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MathUtil {
    public static List<Vec3> distributePointsOnTriangle(Vec3 pos1, Vec3 pos2, Vec3 pos3, int numPoints) {
        List<Vec3> points = new ArrayList<>();
        Random random = new Random();
        double[] barycentricCoords = new double[3];

        for (int i = 0; i < numPoints; i++) {
            // 在参考三角形中生成一个随机点
            double r1 = random.nextDouble();
            double r2 = random.nextDouble();

            // 确保r1 + r2 <= 1
            if (r1 + r2 > 1) {
                r1 = 1 - r1;
                r2 = 1 - r2;
            }

            // 计算三角形内部的随机点的坐标
            barycentricCoords[0] = 1 - r1 - r2;
            barycentricCoords[1] = r1;
            barycentricCoords[2] = r2;

            // 将叉积坐标转换为笛卡尔坐标
            double x = pos1.x * barycentricCoords[0] + pos2.x * barycentricCoords[1] + pos3.x * barycentricCoords[2];
            double y = pos1.y * barycentricCoords[0] + pos2.y * barycentricCoords[1] + pos3.y * barycentricCoords[2];
            double z = pos1.z * barycentricCoords[0] + pos2.z * barycentricCoords[1] + pos3.z * barycentricCoords[2];

            points.add(new Vec3(x, y, z));
        }

        return points;
    }

    public static Vector3f perpendicularFootOfPointToLine(Vector3f lineStar, Vector3f lineEnd, Vector3f point) {
        Vector3f AP = new Vector3f(point).sub(lineStar);
        Vector3f AB = new Vector3f(lineEnd).sub(lineStar);
        float t = AP.dot(AB) / AB.dot(AB);
        return new Vector3f(lineStar).add(AB.mul(t));
    }
}
